package com.example.chat.controller;

import com.example.chat.domain.dto.AiChatRequest;
import com.example.chat.result.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
@CrossOrigin
@Tag(name = "ai聊天相关接口")
@Slf4j
public class ChatAiController {

    @Autowired
    private  ChatClient chatClient;

    private final ChatMemory chatMemory = new InMemoryChatMemory();

    @PostMapping(value = "/chat",produces = "text/html;charset=UTF-8")
    public Flux<String> chatAi(@RequestBody AiChatRequest aiChatRequest){
        String s = aiChatRequest.getSessionId().toString();
        log.info("ID为{}的用户进行AI提问：{}",s.substring(s.length()-4),aiChatRequest.getMessage());
        MessageChatMemoryAdvisor messageChatMemoryAdvisor = new MessageChatMemoryAdvisor(chatMemory, aiChatRequest.getSessionId(), 50);
        Flux<String> content = chatClient.prompt()
                .user(aiChatRequest.getMessage())
                .advisors(messageChatMemoryAdvisor)
                .stream()
                .content();
        return content;
    }
}
